package com.mo.sp06.filter;

import javax.servlet.http.HttpServletRequest;

import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.mo.web.util.JsonResult;

@Component
public class LoginFilter extends ZuulFilter{

    /**
     * 过滤器类型
     * @return
     */
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }


    /**
     * 过滤器序号--执行顺序
     * @return
     */
    @Override
    public int filterOrder() {
        //该过滤器顺序要 > 5，才能得到 serviceid
        return FilterConstants.PRE_DECORATION_FILTER_ORDER+1;
    }


    @Override
    public boolean shouldFilter() {
        //对指定的serviceid过滤，如果要过滤所有服务，直接返回 true
        RequestContext ctx = RequestContext.getCurrentContext();
        String serviceId = (String) ctx.get(FilterConstants.SERVICE_ID_KEY);

        return serviceId.equalsIgnoreCase("item-service");


    }






    @Override
    public Object run() throws ZuulException {
        //获取request对象
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest req = ctx.getRequest();
        String token = req.getParameter("token");
        if (token == null) {
            //此设置会阻止请求被路由到后台微服务
            ctx.setSendZuulResponse(false);
            //向客户端发送响应：
            String json=JsonResult.err()
                    .code(JsonResult.NOT_LOGIN)
                    .msg("Not Login!没有登录！")
                    .toString();
            //http协议头属性：Content-Type：
            ctx.addZuulResponseHeader("Content-Type",
                    "application/json;charset=UTF-8");
            ctx.setResponseBody(json);
        }

            return null;  //当前zuul版本中，没有使用这个返回值
    }





}
